/*
 * FileName：CacheUtils.java
 * <p>
 * Copyright (c) 2017-2020 <a href="">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koine.common.util;

import com.koine.common.spring.SpringContextHolder;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;

/**
 * @author hermit
 * @version 2.0
 * @date 2018-04-17 10:54:58
 */
public class CacheUtils {
    private static CacheManager cacheManager = null;
    private static final String DEFAULT_CACHE = "wxCache";

    // 获取连接
    @SuppressWarnings("unchecked")
    private static CacheManager getCacheManager() {
        if (cacheManager == null) {
            synchronized (CacheUtils.class) {
                if (cacheManager == null) {
                    cacheManager = SpringContextHolder.getBean(EhCacheCacheManager.class);
                }
            }
        }
        return cacheManager;
    }

    /**
     * 获取WX_CACHE缓存
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        return get(DEFAULT_CACHE, key);
    }

    /**
     * 写入WX_CACHE缓存
     *
     * @param key
     * @return
     */
    public static void put(String key, Object value) {
        put(DEFAULT_CACHE, key, value);
    }

    /**
     * 从WX_CACHE缓存中移除
     *
     * @param key
     * @return
     */
    public static void remove(String key) {
        remove(DEFAULT_CACHE, key);
    }

    /**
     * 获取缓存
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, String key) {
        Cache.ValueWrapper valueWrapper = getCacheManager().getCache(cacheName).get(key);
        return null == valueWrapper ? null : valueWrapper.get();
    }

    /**
     * 写入缓存
     *
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, String key, Object value) {
        getCacheManager().getCache(cacheName).put(key, value);
    }

    /**
     * 从缓存中移除
     *
     * @param cacheName
     * @param key
     */
    public static void remove(String cacheName, String key) {
        getCacheManager().getCache(cacheName).evict(key);
    }
}
